//
//  ViewController.m
//  12.KVO的本质
//
//  Created by 梁森 on 2020/2/11.
//  Copyright © 2020 梁森. All rights reserved.
//

#import "ViewController.h"

#import "Person.h"
#import <objc/runtime.h>

@interface ViewController ()

@property (nonatomic, strong) Person * p;;


@end

@implementation ViewController
- (void)printMethodNamesOfClass:(Class)cls
{
    unsigned int count;
    // 获得方法数组
    Method *methodList = class_copyMethodList(cls, &count);
    
    // 存储方法名
    NSMutableString *methodNames = [NSMutableString string];
    
    // 遍历所有的方法
    for (int i = 0; i < count; i++) {
        // 获得方法
        Method method = methodList[i];
        // 获得方法名
        NSString *methodName = NSStringFromSelector(method_getName(method));
        // 拼接方法名
        [methodNames appendString:methodName];
        [methodNames appendString:@", "];
    }
    
    // 释放
    free(methodList);
    
    // 打印方法名
    NSLog(@"%@ %@", cls, methodNames);
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor greenColor];
    
    self.p = [Person new];
    self.p.age = 28;
    
    NSLog(@"IMP:%p", [self.p methodForSelector:@selector(setAge:)]);
    [self printMethodNamesOfClass:object_getClass(self.p)];
    
    NSKeyValueObservingOptions optons = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
    [self.p addObserver:self forKeyPath:@"age" options:optons context:nil];
    
    NSLog(@"IMP:%p", [self.p methodForSelector:@selector(setAge:)]);
    [self printMethodNamesOfClass:object_getClass(self.p)];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    NSLog(@"%@", change);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    self.p.age = 18;
}


@end
